package com.mirror.tk.framework.common.web.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import net.coobird.thumbnailator.Thumbnails;

/**
 *
 * 按比例缩放图片
 *
 * ********************* 使用 ************************
 * 1、原始图片url
 http://xx.xx.xx.xx/xx/xx/abc.jpg

 2、缩略图片url,参数说明，w-宽，h-高
 http://xx.xx.xx.xx/xx/xx/abc.jpg?{w}x{h}

 3、例：限制图片返回宽度不超过200，高度不超过300
 http://xx.xx.xx.xx/xx/xx/abc.jpg?200x300
 *
 ****************** 配置 **************************
 * application.properties 配置
 webapp的绝对路径，生成的缩略图将放在 webapp.dir + url的pach 路径下
 webapp.dir=
 * servlet 配置
 <servlet>
     <servlet-name>thumbnails</servlet-name>
     <servlet-class>com.mirror.tk.framework.common.web.servlet.ThumbnailsServlet</servlet-class>
     <init-param>
     <param-name>config</param-name>
     <param-value>application.properties</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
     <servlet-name>thumbnails</servlet-name>
     <url-pattern>/attch/*</url-pattern>
 </servlet-mapping>
 */
public class ThumbnailsServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	private static final Logger logger = LogManager.getLogger(ThumbnailsServlet.class);

    private static final String paramName="config";

    private String webappDir ="";

    //输出文件
    private void outFile(HttpServletResponse resp, File file) {
        FileInputStream fis=null;
        try{
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int red=-1;
            while ((red = fis.read(b)) !=-1 ){
                resp.getOutputStream().write(b, 0, red);
            }
        } catch (Exception ex){
            ex.printStackTrace();
        }finally {
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        Properties p = new Properties();
        try {
            p.load(ThumbnailsServlet.class.getClassLoader().getResourceAsStream(config.getInitParameter(paramName)));
            webappDir = p.getProperty("webapp.dir");
            if(StringUtils.isBlank(webappDir) || new File(webappDir).exists()==false){
                throw new RuntimeException("ThumbnailsServlet servlet init error webappDir: "+ webappDir +" is not found");
            }
        } catch (Exception e) {
            throw new RuntimeException("ThumbnailsServlet servlet init error", e);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解析参数组装路径
        String query=req.getQueryString();
        String path = req.getServletPath()+req.getPathInfo();
        int li = path.lastIndexOf(".");
        path = path.substring(0, li)+(query==null ? "" : "_"+query)+path.substring(li);
        logger.debug("path:{}", path);
        //查找是否有文件，如果有文件之间返回
        File imageFile = new File(webappDir +path);
        if(imageFile.exists() && imageFile.isFile()){
            outFile(resp, imageFile);
            return;
        }
        //没有文件，验证参数，不正确-返回
        if(StringUtils.isBlank(query)){
            logger.warn("query is blank, query:{}", query);
            return ;
        }
        String[] wh = query.split("x");
        if(wh.length!=2){
            logger.warn("query format error, query:{}", query);
            return;
        }
        //读取原文件，原文件没有，返回
        File originalFile = new File(webappDir +req.getServletPath()+req.getPathInfo());
        if(originalFile.isFile() ==false || originalFile.exists()==false){
            logger.warn("Original File Is Not Found FilePath:{}", originalFile.getPath());
            return;
        }
        //有原文件，按参数生成缩略图，返回并写磁盘
        try {
            Thumbnails.of(originalFile).size(Integer.parseInt(wh[0]), Integer.parseInt(wh[1])).toFile(imageFile);
            logger.debug("Create Thumbnails Success : {}", imageFile.getPath());
            outFile(resp, imageFile);
        } catch (Exception e) {
            logger.error("create thumbnails error image path:"+imageFile.getPath(), e);
        }
    }

}
